//
//  ORHomeViewController.m
//  News
//
//  Created by rimi on 2016/12/5.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "ORHomeViewController.h"
#import "ORRecommendViewController.h"
#import "ORCustomTableViewCell.h"
#import "ORDetailViewController.h"
#import "ORScrollView.h"
#import "ORChannelViewController.h"
#import "DataSourceModel.h"
#import "ORAnecdoteViewController.h"
#import <UIKit+AFNetworking.h>

@interface ORHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic, copy) ORScrollView *scrollViews; // 滚动视图

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArray; //

@property (nonatomic, strong) NSArray *recommendedArray; // 实时推荐

@property (nonatomic, assign) CGFloat height;

@property (nonatomic, strong) UIButton *backHeaderButton; // 返回头部

@property (nonatomic, strong) NSMutableArray *listArray; // 列表数据

@property (nonatomic, strong) NSArray *anecdoteArray; // 滚动视图数据

@property (nonatomic, strong) NSMutableArray *imageUrlArray;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UILabel *errorLabel;

@end

@implementation ORHomeViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //  判断网络状态
    if ( [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        self.tableView.tableHeaderView = self.errorLabel;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self initWith];
    [self initializeDataSource];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"频道"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
}

-(void)click:(UIBarButtonItem *)sender{
    ORChannelViewController *channel = [[ORChannelViewController alloc]init];
    channel.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:channel animated:  YES];
    channel.hidesBottomBarWhenPushed = YES;
}

-(void)initWith{
    self.listArray = [NSMutableArray array];
    // 注册上拉和下拉的方法
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(pullUpLoagMore)];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新
    [self initializeDataSource];

        if ( [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [self showRoundProgressWithTitle:@"加载中···"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self showErrorWithTitle:@"加载失败!" autoCloseTime:1];
            });
        }
        [self.tableView.mj_header endRefreshing];
    }];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.backHeaderButton];
}

-(void)initializeDataSource{
    _page = 1;
    // 网络请求
    [self initDataWithPage:_page withSuccess:^(id respondsObject) {
       
        [self scrollViewWirh];
        
        self.listArray = [respondsObject[@"newslist"]mutableCopy];
        [ORSingTO shareinfo].arrayTitle = respondsObject[@"newslist"];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            
            ORCustomTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            
            [cell.collectionView reloadData];
        });
    }];
}

-(void)pullUpLoagMore{
    // 上拉刷新
    self.page++;
    [self initDataWithPage:self.page withSuccess:^(id respondsObject) {
        [self.listArray addObjectsFromArray:respondsObject[@"newslist"]];
        
        if ( [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [self showRoundProgressWithTitle:@"加载中···"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self showErrorWithTitle:@"加载失败!" autoCloseTime:1];
            });
            [self.tableView reloadData];
        }
        // 让footer停止刷新
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)initDataWithPage:(NSInteger)page withSuccess:(void (^)(id respondsObject))success {
    
    NSDictionary *dic = @{@"num":@(20),@"page":[NSString stringWithFormat:@"%ld",page]};
    NSString  *url=@"http://apis.baidu.com/txapi/weixin/wxhot";
    AFHTTPSessionManager  *maneger=[AFHTTPSessionManager manager];
    
    [maneger.requestSerializer setValue:@"b0468eba387fbccb6b770886063c9814" forHTTPHeaderField:@"apikey"];
    
    maneger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    
    [maneger GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

-(void)scrollViewWirh{
    
    self.imageUrlArray = [NSMutableArray array];
    
    NSDictionary *dic = @{@"key":@"31dc62d724d14f38bb1d5bdea0a03ea6",@"rows":@(20),@"page":@"1"};
    
    [ORNetWorkRequestManager getMethod:@"http://api.avatardata.cn/QiWenNews/Query" withParames:dic Success:^(id respondObject) {
        self.anecdoteArray = [respondObject[@"result"] mutableCopy];
        for (int i = 0; i < 6; i++) {
            
            NSDictionary *dic = self.anecdoteArray[i];
            
            NSString *url = dic[@"picUrl"];
            [self.imageUrlArray addObject:url];
//            NSLog(@"%@", self.imageUrlArray);
        }
        NSArray *imgArr = self.imageUrlArray;
        
        _scrollViews = nil;
        _scrollViews = [ORScrollView roundScrollViewWithFrame:AAdaptionRect(0, 0, kBaseWidth, 200) imageArr:imgArr timerWithTimeInterval:2 imageClick:^(NSInteger imageIndex) {
            ORAnecdoteViewController *aneVC = [[ORAnecdoteViewController alloc]init];
            aneVC.url = self.anecdoteArray[imageIndex][@"url"];
            aneVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aneVC animated:YES];
            aneVC.hidesBottomBarWhenPushed = NO;
        }];
        _scrollViews.curPageControlColor = MainColor;
        _scrollViews.otherPageControlColor = [UIColor whiteColor];
        
        _tableView.tableHeaderView = _scrollViews;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } Failure:^(NSError *error) {
        
    }];
}

// 根据tableView的偏移量，判断按钮是否出现
- (void)backHeaderShowOrDisappearOffsetY:(CGFloat)y {
    if (y <= self.view.bounds.size.height) {
        [UIView animateWithDuration:0.5 animations:^{
            self.backHeaderButton.alpha = 0;
        } completion:^(BOOL finished) {
            [self.backHeaderButton removeFromSuperview];
        }];
    }else {
        [self.view addSubview:self.backHeaderButton];
        [UIView animateWithDuration:0.5 animations:^{
            self.backHeaderButton.alpha = 1;
        }];
    }
}

#pragma mark - 响应方法
// 返回头部点击事件
-(void)backHeaderButtonWirh:(UIButton *)sender{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat y = scrollView.contentOffset.y;
    [self backHeaderShowOrDisappearOffsetY:y];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return _listArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return AAdaptation(120);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *rese = @"UITableViewCell";
    ORCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rese];
    if (!cell) {
        cell = [[ORCustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rese];
    }
    if (indexPath.section == 0) {
        cell.isHidde = NO;
        cell.nameLabels.text = @"实时推荐";
    }else if (indexPath.section == 1){
        cell.isHidde = YES;
        cell.realtype.text = _listArray[indexPath.row][@"description"];
        NSString *urlimg = _listArray[indexPath.row][@"picUrl"];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:urlimg] placeholderImage:[UIImage imageNamed:@"4"]];
        cell.titleLabel.text = _listArray[indexPath.row][@"title"];
        cell.author_name.text = _listArray[indexPath.row][@"ctime"];
    }
    
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

#pragma mark - tableview 点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ORDetailViewController *detail = [[ORDetailViewController alloc]init];
    detail.url = _listArray[indexPath.row][@"url"];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    detail.hidesBottomBarWhenPushed = NO;
}

#pragma mark - getter

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth, kBaseHeight - 100) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIButton *)backHeaderButton{
    if (!_backHeaderButton) {
        _backHeaderButton = [[UIButton alloc]initWithFrame:AAdaptionRect(CGRectGetMaxX(self.view.frame) - 50, kBaseHeight/AAdaptationWidth() - 170, 40, 40)];
        [_backHeaderButton setImage:[UIImage imageNamed:@"回到顶部"] forState:UIControlStateNormal];
        _backHeaderButton.alpha = 0;
        [_backHeaderButton addTarget:self action:@selector(backHeaderButtonWirh:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backHeaderButton;
}

-(UILabel *)errorLabel{
    if (!_errorLabel) {
        _errorLabel = [[UILabel alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth, 40)];
        _errorLabel.backgroundColor = [UIColor colorWithRed:248/255.f green:200/255.f blue:52/255.f alpha:0.6];
        _errorLabel.textAlignment = NSTextAlignmentCenter;
        _errorLabel.text = @"你已进入二次元!";
    }
    return _errorLabel;
}

@end
